#include <rtdevice.h>
#include <rtthread.h>
#include <board.h>
#include <dev_spi_flash.h>
#include <drv_spi.h>
#include "dev_spi_flash_sfud.h"
#include <dfs_fs.h>
#include <fal.h>


#define SPI_BUS_NAME "spi2"
#define SPI_DEVICE_NAME "spi20"
#define SPI_FLASH_DEVICE_NAME "W25Q64S"

static void cs_pin_control(int cs)
{
    board_write_spi_cs(BOARD_SPI_CS_PIN, cs); 
}


int spi_flash_init(void)
{
    /* 挂载SPI Flash设备到软SPI1总线 */
    struct rt_spi_device * spi_dev=(struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
    RT_ASSERT(rt_spi_bus_attach_device_cspin(spi_dev, "spi20", "spi2", BOARD_SPI_CS_PIN, cs_pin_control)==RT_EOK);
  
    RT_ASSERT(RT_NULL != rt_sfud_flash_probe(SPI_FLASH_DEVICE_NAME, SPI_DEVICE_NAME));

    // fal_init();
    // fal_blk_device_create(SPI_SECT_DEVICE_NAME);

    /* 挂载文件系统 */
    #ifdef BSP_USING_FATFS_ROOTFS

    int try=10;
    while(dfs_mount(SPI_FLASH_DEVICE_NAME, "/spi", "elm", 0, 0) != 0)
    {
        rt_kprintf("mount to '/spi' failed! try again...\n");

        rt_thread_mdelay(100);
        try--;
        if(try<=0) break;
    }
    rt_kprintf("mount to '/spi' success!\n");
    #endif

_exit:
    return 0;
}
INIT_APP_EXPORT(spi_flash_init); 